/*
 * SimulationDialog.java
 *
 * Created on Pondelok, 2007, november 12, 0:01
 */

package gui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import logic.JSimulation;
import logic.SimulationRunState;
import logic.Statistic;
import logic.SwingSimulationOneRun;

/**
 *
 * @author  alvin
 */
public class SimulationDialog extends javax.swing.JDialog 
               implements SwingSimulationOneRun.StateChangeListener  {
    
    /** Creates new form SimulationDialog */
    public SimulationDialog(javax.swing.JFrame owner) {
        super(owner, true);
        initComponents();
    }

    private boolean running = false;
    SwingSimulationOneRun simulation;
    LinkedList<Statistic> results;
    
    public void start() {
        setLocationRelativeTo(getOwner());
        setVisible(true);
        System.out.println("SimulationDialog.start()");

        running = false;
        startStopBtn.setText(running ? "Stop" : "Start");
        startStopBtn.setEnabled(true);

        resultPane.setEnabled(false);
        resultText.setEnabled(true);
        saveCSVBtn.setEnabled(false);
        saveXMLBtn.setEnabled(false);
        closeBtn.setEnabled(false);
        resultText.setText("");
        
        if (results != null)
            results.clear();
        
        simulation = new SwingSimulationOneRun();
        simulation.addStateChangeListener(this);
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        simulationProgress = new javax.swing.JProgressBar();
        startStopBtn = new javax.swing.JButton();
        simulationStateDesc = new javax.swing.JLabel();
        resultPane = new javax.swing.JScrollPane();
        resultText = new javax.swing.JTextArea();
        closeBtn = new javax.swing.JButton();
        saveXMLBtn = new javax.swing.JButton();
        saveCSVBtn = new javax.swing.JButton();
        resultsLbl = new javax.swing.JLabel();

        setTitle("Simulation");
        simulationProgress.setStringPainted(true);

        startStopBtn.setText("Start");
        startStopBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startStopBtnActionPerformed(evt);
            }
        });

        simulationStateDesc.setText("state");

        resultText.setColumns(20);
        resultText.setEditable(false);
        resultText.setRows(5);
        resultPane.setViewportView(resultText);

        closeBtn.setText("Close");
        closeBtn.setMaximumSize(new java.awt.Dimension(92, 25));
        closeBtn.setMinimumSize(new java.awt.Dimension(92, 25));
        closeBtn.setPreferredSize(new java.awt.Dimension(92, 25));
        closeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeBtnActionPerformed(evt);
            }
        });

        saveXMLBtn.setText("Save XML");

        saveCSVBtn.setText("Save CSV");
        saveCSVBtn.setMaximumSize(new java.awt.Dimension(92, 25));
        saveCSVBtn.setMinimumSize(new java.awt.Dimension(92, 25));
        saveCSVBtn.setPreferredSize(new java.awt.Dimension(92, 25));

        resultsLbl.setText("Results");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(resultPane, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                    .addComponent(simulationStateDesc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                    .addComponent(simulationProgress, javax.swing.GroupLayout.DEFAULT_SIZE, 454, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(resultsLbl)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 345, Short.MAX_VALUE)
                        .addComponent(startStopBtn))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveCSVBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(saveXMLBtn)
                        .addGap(15, 15, 15)
                        .addComponent(closeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(simulationStateDesc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(simulationProgress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startStopBtn)
                    .addComponent(resultsLbl))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resultPane, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveXMLBtn)
                    .addComponent(saveCSVBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void closeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeBtnActionPerformed
        setVisible(false);
    }//GEN-LAST:event_closeBtnActionPerformed

    private void startStopBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startStopBtnActionPerformed
        if (running) {
            startStopBtn.setEnabled(false);
            System.out.println("Stop simulation..");
            simulation.stopExecuting();
        } else {
            startStopBtn.setText("Stop");
            simulation.execute();
            running = true;
        }
        
    }//GEN-LAST:event_startStopBtnActionPerformed

    public void StateChanged(SimulationRunState newState) {
        String desc = newState.getStateDescription();
        switch (newState.getState()) {
            case SimulationRunState.STATE_RUNNING:
                int done = newState.getDoneTasksCount();
                int all = newState.getTasksCount();
                desc = desc +
                        " finished " + Integer.toString(done) +
                        " from " + Integer.toString(all) + " tasks";
                simulationProgress.setValue(done*100/all);
                break;
            case SimulationRunState.STATE_INIT:
                simulationProgress.setValue(0);
                break;
            case SimulationRunState.STATE_FINISHING:
            case SimulationRunState.STATE_FINISHED:
                simulationProgress.setValue(100);
                break;
            case SimulationRunState.STATE_WAITING_FOR_START:
                simulationProgress.setValue(0);
                break;
            default:
                break;
        }
        simulationStateDesc.setText(desc + ".");
    }

    public void showResults() {
        resultText.setText("");
        if (results != null) {
            for (Statistic stat : results) {
                String line = stat.getEntityName() +
                        ": " + stat.typeToStr() +
                        " " + Double.toString(stat.getMeanValue());
                resultText.append(line + "\n");
            }
        }
    }
    
    public void simulationFinished() {
        startStopBtn.setEnabled(false);
        try {
            if (!JSimulation.isForcedStop()) {
                results = simulation.get();
                System.out.println("Showing simulation results " + results.size());
                saveCSVBtn.setEnabled(true);
                saveXMLBtn.setEnabled(true);
                showResults();
            } else {
                System.out.println("Forced stop");
                results = null;
            }
            closeBtn.setEnabled(true);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (ExecutionException ex) {
            ex.printStackTrace();
        }
    }

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeBtn;
    private javax.swing.JScrollPane resultPane;
    private javax.swing.JTextArea resultText;
    private javax.swing.JLabel resultsLbl;
    private javax.swing.JButton saveCSVBtn;
    private javax.swing.JButton saveXMLBtn;
    private javax.swing.JProgressBar simulationProgress;
    private javax.swing.JLabel simulationStateDesc;
    private javax.swing.JButton startStopBtn;
    // End of variables declaration//GEN-END:variables
    
}
